import { CustomerModel } from '@/models/customer'
import CustomerTable from '@/pages/Customer/components/CustomerTable'
import CustomerUpdateModal from '@/pages/Customer/components/CustomerUpdateModal'
import { CustomerUpdateDTO, CustomerVO, saveCustomer, updateCustomer } from '@/services/CustomerService'
import { PageContainer } from '@ant-design/pro-components'
import { ActionType } from '@ant-design/pro-table'
import { message } from 'antd'
import { useRef, useState } from 'react'

const Customer = () => {
  // 编辑操作
  const [updateModalState, setUpdateModalState] = useState(false)
  const [currentCustomer, setCurrentCustomer] = useState<CustomerVO | undefined>()
  // 表格引用
  const tableRef = useRef<ActionType>()
  const updateEvent = async (record: CustomerVO) => {
    // 打开模态框
    setCurrentCustomer(record)
    setUpdateModalState(true)
  }

  const saveEvent = async () => {
    // 打开模态框
    setUpdateModalState(true)
  }

  const onUpdateModalChange = async (state: boolean) => {
    if (state) {
      CustomerModel.state.uploadUrl = undefined
      setUpdateModalState(state)
    } else {
      await setCurrentCustomer(undefined)
      setUpdateModalState(state)
    }
  }
  // 提交修改
  const onUpdateFinish = async (formData: any) => {
    let dto: CustomerUpdateDTO = JSON.parse(JSON.stringify(formData))
    dto.attachUrl = CustomerModel.state.uploadUrl
    // 字段处理
    if (currentCustomer) {
      updateCustomer(dto).then((response) => {
        if (response) {
          message.success('操作成功')
          tableRef.current?.reload()
          return
        }
        message.error('更新失败')
      })
    } else {
      saveCustomer(dto).then((response) => {
        if (response) {
          message.success('操作成功')
          tableRef.current?.reload()
          return
        }
        message.error('更新失败')
      })
    }
    return true
  }

  return (
    <PageContainer title="客资">
      {/*客资表格 开始*/}
      <CustomerTable tableRef={tableRef} onSave={saveEvent} onUpdate={updateEvent} />
      {/*客资表格 结束*/}

      {/*修改模态框 开始*/}
      <CustomerUpdateModal
        customer={currentCustomer}
        open={updateModalState}
        onOpenChange={onUpdateModalChange}
        onFinish={onUpdateFinish}
      />
      {/*修改模态框 结束*/}
    </PageContainer>
  )
}

export default Customer
